<template>
  <z-modal
      v-bind="modalOption"
      @ok="handleOk"
      @cancel="handleCancel"
      cancelText="关闭"
  >
    <a-spin :spinning="confirmLoading">
      <a-form-model layout="horizontal" labelAlign="right" ref="ruleForm" :label-col="labelCol" :wrapper-col="wrapperCol" :model="form" :rules="validatorRules">
        <a-form-model-item label="商品名称" prop="goodsName">
          <a-input placeholder="请输入商品名称" :disabled="disableSubmit" v-model.trim="form.goodsName"/>
        </a-form-model-item>
        <a-form-model-item label="商品分类" prop="goodsType">
          <a-select :default-value="form.goodsType" style="width: 100%" :disabled="disableSubmit" @change="selectChange">
            <a-select-option value="-1">请选择</a-select-option>
            <a-select-option v-for="type in goodsType" :key="type.id">
              {{ type.typeName }}
            </a-select-option>
          </a-select>
        </a-form-model-item>
        <a-form-model-item label="价格" prop="price">
          <a-input-number placeholder="请输入价格" :disabled="disableSubmit" style="width: 100%" v-model.trim="form.price" :min="0" :precision="2"/>
        </a-form-model-item>
        <a-form-model-item label="销量" prop="salesNum">
          <a-input-number placeholder="请输入销量" :disabled="disableSubmit" style="width: 100%" v-model.trim="form.salesNum" :min="0"/>
        </a-form-model-item>
        <a-form-model-item label="联系人" prop="contacts">
          <a-input placeholder="请输入联系人" :disabled="disableSubmit" v-model.trim="form.contacts"/>
        </a-form-model-item>
        <a-form-model-item label="电话" prop="phone">
          <a-input placeholder="请输入电话" :disabled="disableSubmit" v-model.trim="form.phone"/>
        </a-form-model-item>
        <a-form-model-item label="图片">
          <a-upload
              list-type="picture-card"
              :file-list="fileList1"
              :multiple="true"
              @preview="handlePreview"
              @change="handleChange1"
              :customRequest="onUpload1"
              :disabled="disableSubmit"
          >
            <div v-if="fileList1.length < 3 && !disableSubmit">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
          <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancelView">
            <img alt="example" style="width: 100%" :src="previewImage" />
          </a-modal>
        </a-form-model-item>
        <a-form-model-item label="上架状态" prop="onlineFlag">
          <z-dict-select-tag v-model="form.onlineFlag" placeholder="请选择上架状态" :disabled="disableSubmit" dictCode="onlineStat"/>
        </a-form-model-item>
        <a-form-model-item label="首页显示" prop="isBanner">
          <a-switch :checked="isBanner" @change="toggleBanner" :disabled="disableSubmit"/>
        </a-form-model-item>
        <a-form-model-item label="详情图">
          <a-upload
              list-type="picture-card"
              :file-list="fileList2"
              :multiple="true"
              @preview="handlePreview"
              @change="handleChange2"
              :disabled="disableSubmit"
              :customRequest="onUpload2"
          >
            <div v-if="fileList2.length < 10 && !disableSubmit">
              <a-icon type="plus" />
              <div class="ant-upload-text">
                上传
              </div>
            </div>
          </a-upload>
        </a-form-model-item>
      </a-form-model>
    </a-spin>
  </z-modal>
</template>

<script>
import ModalFormMixin from '@/mixins/ModalFormMixin'
import { Upload as AUpload } from 'ant-design-vue'
import ZDictSelectTag from '@/components/dict/ZDictSelectTag'
import { getAction, postAction } from '@/services/manage'

export default {
  name: 'GoodsModal',
  mixins: [ModalFormMixin],
  components: {
    ZDictSelectTag,
    AUpload
  },
  data() {
    return {
      title: '操作',
      model: {},
      goodsType: [],
      fileList1: [],
      fileList2: [],
      confirmLoading: false,
      previewVisible: false,
      previewImage: '',
      form: {
        onlineFlag: '10'
      },
      isBanner: false,
      validatorRules: {
        goodsName: [{ required: true, message: '请输入商品名称!' }],
        goodsType: [{ required: true, message: '请选择商品分类!' }],
        price: [{ required: true, message: '请输入商品价格!' }],
        salesNum: [{ required: true, message: '请输入商品销量!' }],
        contacts: [{ required: true, message: '请输入联系人!' }],
        phone: [{ required: true, message: '请输入联系人电话!' }]
      },
      disableSubmit: false,
      url: {
        add: '/doc/goods/v1/add',
        edit: '/doc/goods/v1/edit'
      }
    }
  },
  methods: {
    addBefore(row) {
      this.init(row)
    },
    editBefore(row) {
      this.init(row)
      if (row.pics) {
        // 处理图片
        const pics1 = row.pics.split(',')
        const picObjs1 = JSON.parse(row.textMap['pics$DICT_TEXT_'])
        for (let i = 0; i < pics1.length; i++) {
          const pic1 = picObjs1[i]
          this.fileList1.push({
            uid: pic1.fileNo,
            name: pic1.fileName,
            status: 'done',
            url: pic1.absolutePath,
            response: pic1.fileNo
          })
        }
      }
      if (row.detailPics) {
        // 处理图片
        const pics2 = row.detailPics.split(',')
        const picObjs2 = JSON.parse(row.textMap['detailPics$DICT_TEXT_'])
        for (let i = 0; i < pics2.length; i++) {
          const pic2 = picObjs2[i]
          this.fileList2.push({
            uid: pic2.fileNo,
            name: pic2.fileName,
            status: 'done',
            url: pic2.absolutePath,
            response: pic2.fileNo
          })
        }
      }
    },
    init(row) {
      this.confirmLoading = true
      // 加载商品分类
      getAction('/doc/goodstype/v1/list').then(res => {
        this.confirmLoading = false
        this.goodsType = res.result
      })
      this.isBanner = row && row.homeFlag === '1'
    },
    selectChange(val) {
      this.form.goodsType = val
    },
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await this.getBase64(file.originFileObj)
      }
      this.previewImage = file.url || file.preview
      this.previewVisible = true
    },
    handleCancelView() {
      this.previewVisible = false
    },
    handleChange1({ file, fileList }) {
      this.fileList1 = fileList
      const pics = []
      for (let i = 0; i < fileList.length; i++) {
        pics.push(fileList[i].response)
      }
      this.form.pics = pics.join()
    },
    onUpload1(info) {
      const formData = new FormData()
      formData.append('file', info.file)
      postAction('/doc/goods/v1/upload', formData).then(res => {
        if (res.success) {
          this.$message.success('上传成功')
          info.onSuccess(res.result, info.file)
        }
      })
    },
    handleChange2({ file, fileList }) {
      this.fileList2 = fileList
      const pics = []
      for (let i = 0; i < fileList.length; i++) {
        pics.push(fileList[i].response)
      }
      this.form.detailPics = pics.join()
    },
    onUpload2(info) {
      const formData = new FormData()
      formData.append('file', info.file)
      postAction('/doc/goods/v1/upload', formData).then(res => {
        if (res.success) {
          this.$message.success('上传成功')
          info.onSuccess(res.result, info.file)
        }
      })
    },
    getBase64(file) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.readAsDataURL(file)
        reader.onload = () => resolve(reader.result)
        reader.onerror = error => reject(error)
      })
    },
    toggleBanner(checked) {
      this.isBanner = checked
      this.form.homeFlag = checked ? '1' : '0'
    },
    submitBefore() {
      if (this.fileList1.length === 0) {
        return new Promise((resolve, reject) => { reject({ message: '请上传商品图片' }) })
      }
    }
  }
}
</script>
